<script setup lang="ts">
import {computed, onMounted, ref} from "vue";
import { ElMessage } from 'element-plus'
import {
  DeleteMusic,
  GetMusicList,
  GetSongInfo,
  SelectMusicFiles,
  ChangeLoop,
  ChangePrivate
} from "../../../../wailsjs/go/view/App";
import {useBaseStore} from "@/stores/base.ts";
import {
  DArrowLeft,
  DArrowRight,
  Fold,
  Plus,
  Refresh,
  Star,
  StarFilled,
  VideoPause,
  VideoPlay
} from "@element-plus/icons-vue";
import {tables} from "../../../../wailsjs/go/models.ts";

const baseStore = useBaseStore()

const audioRef =  ref<HTMLAudioElement | null>(null)
const currentAudioUrl = ref('')
const currentTime = ref(0)
const duration = ref(0)
const songName = ref("")
const singer = ref("")
const volume = ref(50) // 音量
const isFavourite = ref(false)
const musicList = ref<tables.TarMusic[]>([])
const search = ref("")

//handleAudioEnd 播放完毕时自动加载下一首歌，如果是单曲循环的情况下还是加载当前歌曲
const handleAudioEnd =async ()=>{
  if (baseStore.musicConfig.loopModule =="one"){
    //await loadSong("curr") // 不需要重新加载歌曲
    onSongSeekChangeEvn(0) // 调整播放进度为0，重新开始播放
    // playTrack()
  }else {
    await loadSong("next")
    playTrack()
  }
}
// 点击获取下一首歌
const clickNextBtn = async (str:string)=>{
  await loadSong(str)
  if (audioRef.value) {
    playTrack()
  }
}
// 设置音量
const onVolumeChangeEvn=(val:number)=>{
  if (audioRef.value) {
    audioRef.value.volume = val/100
  }
}
// 跳转到指定时间
const onSongSeekChangeEvn = (val:number)=>{
  if (audioRef.value) {
    audioRef.value.currentTime =val
  }
}

// 更新进度
const updateProgress = () => {
  if (audioRef.value) {
    currentTime.value = audioRef.value.currentTime
  }
}
// 音频加载完成
const onLoadedMetadata = () => {
  if (audioRef.value) {
    duration.value = audioRef.value.duration
  }
}
// 播放指定曲目
const playTrack = () => {
  // 加载后自动播放
  if (audioRef.value) {
    audioRef.value.load()
    audioRef.value.oncanplay = () => {
      audioRef.value?.play()
      baseStore.musicConfig.isPlaying = true
    }
  }
}
// 播放/暂停
const togglePlay = () => {
  if (!audioRef.value) return

  if (baseStore.musicConfig.isPlaying) {
    audioRef.value.pause()
  } else {
    audioRef.value.play()
  }
  baseStore.musicConfig.isPlaying = !baseStore.musicConfig.isPlaying
}
onMounted( async ()=>{
  await loadSong("curr")
  musicList.value =await GetMusicList(baseStore.showPrivate)
} )
// 加载歌曲
const loadSong = async (str:string)=>{
  const musicInfo = await GetSongInfo(str)
  if (audioRef.value) {
    currentAudioUrl.value = musicInfo.path
    songName.value = musicInfo.name
    singer.value = musicInfo.singer==''?'未知歌手': musicInfo.singer
    audioRef.value.volume = volume.value/100
  }
}
// clickAddMusic 添加歌曲到数据库中
const clickAddMusic = async ()=>{
  await SelectMusicFiles()
  musicList.value =await GetMusicList(baseStore.showPrivate)
}
const filterTableData = computed(() =>
  musicList.value.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase())
  )
)
const playMusicById =async (musicId:number)=>{
  await loadSong(musicId.toString())
  if (audioRef.value) {
    playTrack()
  }
}
const clickDeleteMusic = async (musicId:number)=>{
  if ( baseStore.musicConfig.currentSongId == musicId.toString() ){
    ElMessage({
      message: '不能删除正在播放的歌曲!',
      type: 'warning',
    })
    return
  }
  await DeleteMusic(musicId.toString())
  musicList.value =await GetMusicList(baseStore.showPrivate)
}
const clickPrivateBtn =async (musicId:number)=>{
  await ChangePrivate(musicId.toString())
  musicList.value =await GetMusicList(baseStore.showPrivate)
}
const clickEditBtn = (musicId:number)=>{
  ElMessage({
    message: '还没想好怎么定义标签功能,写好nas后规划它!',
    type: 'warning',
  })
}
const clickChangeLoopMode =()=>{
  ChangeLoop().then(res =>{
    baseStore.musicConfig.loopModule = res
  })
}

const clickMusicListBtn = async ()=>{
  musicList.value =await GetMusicList(baseStore.showPrivate)
}

</script>

<template>
  <el-drawer class="music-drawer" v-model="baseStore.musicConfig.showDrawer" title="音乐播放器" size="500">
    <audio
      ref="audioRef"
      :src="currentAudioUrl"
      @timeupdate="updateProgress"
      @loadedmetadata="onLoadedMetadata"
      @ended="handleAudioEnd"
    ></audio>
    <template #header="{ close, titleId, titleClass }">
      <div class="flex justify-end mr-3">
        <el-tooltip content="导入歌曲" placement="top">
          <el-button circle :icon="Plus" @click="clickAddMusic">
          </el-button>
        </el-tooltip>
        <el-tooltip content="更新歌曲库" placement="top">
          <el-button circle>
            <SvgIcon name="syncFile" size="16px" />
          </el-button>
        </el-tooltip>
      </div>
    </template>
    <div>
      <!--      分别展示：工具栏、歌曲信息、进度条、操作按钮-->
      <!--      歌曲信息-->
      <div class="flex">
        <div style="width: 200px;height: 100px">
          <div class="font-semibold ">{{ songName }}</div>
          <div class="font-light text-sm ">{{ singer }}</div>
        </div>
        <div style="width: 200px;height: 100px">
          波形信息
        </div>
      </div>
      <!--      进度条-->
      <div class="flex justify-between">
        <el-slider v-model="currentTime" :max="duration" @change="onSongSeekChangeEvn" style="width: 300px" class="inline-block"/>
        <div class="flex ml-2">
          <div class="inline-block mr-3">
            <el-tooltip content="音量" placement="top">
              <SvgIcon name="volumeOn" v-if="volume!=0" />
              <SvgIcon name="volumeOff" v-else  />
            </el-tooltip>
          </div>
          <el-slider v-model="volume" :max="100" size="small" @change="onVolumeChangeEvn" style="width: 80px"  class="inline-block"/>
        </div>
      </div>
      <el-divider />
      <!--      操作按钮-->
      <div class="flex justify-between">
        <div class="flex">
          <el-tooltip content="播放/暂停" placement="top">
            <el-button circle @click="togglePlay" >
              <SvgIcon name="play" v-if="baseStore.musicConfig.isPlaying" size="16"/>
              <SvgIcon name="stop" v-else size="16"/>
            </el-button>
          </el-tooltip>
          <el-tooltip content="上一曲" placement="top">
            <el-button :icon="DArrowLeft" circle @click="clickNextBtn('last')" />
          </el-tooltip>
          <el-tooltip content="下一曲" placement="top">
            <el-button :icon="DArrowRight" circle @click="clickNextBtn('next')" />
          </el-tooltip>
        </div>
        <div class="flex">
          <el-tooltip content="收藏" placement="top">
            <el-button :icon="isFavourite?StarFilled:Star" circle  />
          </el-tooltip>
          <el-tooltip content="循环模式" placement="top">
            <el-button circle @click="clickChangeLoopMode">
              <SvgIcon name="music_one" v-if=" baseStore.musicConfig.loopModule == 'one' " size="16"/>
              <SvgIcon name="music_rang" v-else-if=" baseStore.musicConfig.loopModule == 'loop' "  size="16"/>
              <SvgIcon name="music_random" v-else size="16" />
            </el-button>
          </el-tooltip>
          <el-tooltip content="歌曲列表" placement="top">
            <el-button :icon="Fold" circle @click="clickMusicListBtn"/>
          </el-tooltip>
        </div>
      </div>
      <el-divider />
      <el-table :data="filterTableData" max-height="300">
        <el-table-column prop="name" label="名称" width="150" :show-overflow-tooltip="true"/>
        <el-table-column prop="label" label="标签" />
        <el-table-column fixed="right" label="操作" width="160">
          <template #header>
            <el-input v-model="search" size="small" placeholder="按歌曲名称过滤" />
          </template>
          <template #default="scope">
            <el-link @click="playMusicById(scope.row.id)" underline="never" class="mr-2" >
              <el-text size="small" type="primary">播放</el-text>
            </el-link>
            <el-link @click="clickPrivateBtn(scope.row.id)" underline="never" class="mr-2" >
              <el-text size="small" type="primary">隐藏</el-text>
            </el-link>
            <el-link @click="clickEditBtn(scope.row.id)" underline="never" class="mr-2" >
              <el-text size="small" type="primary">编辑</el-text>
            </el-link>
            <el-link @click="clickDeleteMusic(scope.row.id)" underline="never" class="mr-2" >
              <el-text size="small" type="primary">删除</el-text>
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-drawer>

</template>

<style scoped lang="scss">
::v-deep(.el-drawer__header) {
  margin-bottom: 0;
}
</style>
